package com.szl.yeb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szl.yeb.entity.AdminRole;
import com.szl.yeb.exception.CustomException;
import com.szl.yeb.mapper.MenuRoleMapper;
import com.szl.yeb.mapper.RoleMapper;
import com.szl.yeb.entity.Role;
import com.szl.yeb.service.AdminRoleService;
import com.szl.yeb.service.MenuRoleService;
import com.szl.yeb.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.szl.yeb.common.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szl.yeb.utils.MybatisPlusUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * (Role)表服务实现类
 *
 * @author szl
 * @since 2022-08-24 16:21:28
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private MenuRoleService menuRoleService;

    @Autowired
    private AdminRoleService adminRoleService;

    @Override
    public PageResult getPage(Integer currentPage, Integer size, Role role) {
        Page<Role> page = new Page<>(currentPage, size);

        QueryWrapper<Role> queryWrapper = MybatisPlusUtil.queryWrapperBuilder(role);

        this.page(page, queryWrapper);

        return new PageResult((int) page.getTotal(), page.getRecords());
    }

    @Override
    public List<Role> getRolesByAdminId(Integer adminId) {
        return baseMapper.selectRolesByAdminId(adminId);
    }

    @Override
    public Boolean deleteRoleAndAssociations(Integer rid) {
        //查询是否有用户使用该角色，如果有，则不允许删除
        long count = adminRoleService.count(MybatisPlusUtil.getLQWrapper(AdminRole.class).eq(AdminRole::getRid, rid));
        if(count>0){
            throw new CustomException("存在使用该角色的用户，无法删除");
        }

        Integer result = menuRoleService.updateMenuRoleAssociations(rid, new ArrayList<>());
        return baseMapper.deleteById(rid) > 0 && result > 0;
    }
}

